package volunteer.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.xuegengwang.xuegengwang.R;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import common.BaseActivity;
import common.Constant;
import https.InterNetController;
import https.handler.ErrorPageHandler;
import question.activity.Ask;
import utils.ShowImageUtils;
import view.MyImageLoader;
import volunteer.bean.VolunteerBean;
import volunteer.bean.VolunteerIndexBean;
import se.emilsjolander.stickylistheaders.StickyListHeadersListView;
import volunteer.adapter.VolunteerStickyListHeaderListViewAdapter;

/**
 * Created by wangic on 2017/2/26.
 * vip/normal志愿者首页
 */


@ContentView(R.layout.volunteer_page)
public class Volunteer extends BaseActivity implements View.OnClickListener {
    @ViewInject(R.id.volunteer_page_lv)
    private StickyListHeadersListView listHeadersListView;
    private View header;//头部布局
    private RelativeLayout volunteer_header_layout;//用于计算高度的
    private int measuredHeight;
    private ImageView volunteer_head;//头像
    private ImageView volunteer_head_vip;//vip
    private TextView volunteer_name;//头部名字
    private TextView volunteer_brief;//官方认证咨询员
    private LinearLayout volunteer_header_satisfaction_layout;//满意度布局
    private TextView volunteer_header_attention;//关注量
    private TextView volunteer_header_answered;//回答数
    private TextView volunteer_header_satisfaction;//满意度
    private ImageView volunteer_header_satisfaction_ima;//满意度图片
    private TextView volunteer_header_active;//活跃度
    private ImageView volunteer_header_active_ima;//活跃度图片
    private TextView volunteer_content_department;//院系
    private TextView volunteer_content_major;//专业
    private TextView volunteer_introduction;//个人简介
    private TextView volunteer_content_college;//高校
    private ImageView volunteer_focus;//关注


    private VolunteerStickyListHeaderListViewAdapter stickyListHeaderListViewAdapter;
    private ArrayList<VolunteerBean> arrayList;//志愿者解答和评价数组
    @ViewInject(R.id.volunteer_answer_item_header)
    private RelativeLayout volunteer_answer_item_header;//头部滑动显示背景颜色
    @ViewInject(R.id.volunteer_answer_item_name)
    private TextView volunteer_answer_item_name;//头部名字
    @ViewInject(R.id.volunteer_back)
    private ImageView volunteer_back;//退出按钮
    @ViewInject(R.id.volunteer_ask)
    private TextView volunteer_ask;//立即提问
    private LinearLayout volunteer_introduction_layout;//简介信息
    private ImageView volunteer_more_introduction;//更多个人简介icon
    private boolean isShowIntroduction = false;//是否已经展开个人简介
    private String id;

    private final int GETDATA = 0;
    private final int FOCUS = 1;
    private VolunteerIndexBean.ConsulterBean consulter;
    private ShowImageUtils showImageUtils;

    private String type;

    private boolean changeFocus = false;//用于判断是否被取关

    private ErrorPageHandler myHandler = new ErrorPageHandler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constant.ERROR_CODE_SUCCESS:
                    switch (msg.arg1) {
                        case GETDATA:
                            Gson gson = new Gson();
                            VolunteerIndexBean volunteerIndexBean = gson.fromJson((String) msg.obj, VolunteerIndexBean.class);
                            if (volunteerIndexBean != null) {
                                consulter = volunteerIndexBean.getConsulter();
                                if (consulter != null) {
                                    volunteer_name.setText(consulter.getName());
                                    MyImageLoader.showImage(consulter.getHeadimgurl(), volunteer_head);
                                    volunteer_header_attention.setText(consulter.getAttention() + "人关注");
                                    volunteer_header_answered.setText("解答过" + consulter.getAnswered() + "个问题");
                                    volunteer_header_satisfaction.setText("" + consulter.getSatisfaction());
                                    volunteer_header_active.setText("" + consulter.getActive());
                                    volunteer_content_department.setText(consulter.getDepartment());
                                    volunteer_introduction.setText(consulter.getIntro());
                                    volunteer_content_major.setText(consulter.getMajor());
                                    volunteer_content_college.setText(consulter.getCollege());
                                    volunteer_answer_item_name.setText(consulter.getName());
                                    MyImageLoader.showImage(consulter.getSatisfaction_img(), volunteer_header_satisfaction_ima);
                                    MyImageLoader.showImage(consulter.getActive_img(), volunteer_header_active_ima);
                                    if (consulter.getAttentioned() == 0) {
                                        //未关注
                                        volunteer_focus.setImageResource(R.mipmap.volunteer_focus);
                                    } else {
                                        //已经关注
                                        volunteer_focus.setImageResource(R.mipmap.volunteer_focused);
                                    }
                                }
                                arrayList.clear();
                                List<VolunteerIndexBean.CommentListBean> commentList = volunteerIndexBean.getCommentList();//评论
                                List<VolunteerIndexBean.QuestionListBean> questionList = volunteerIndexBean.getQuestionList();//回答
                                if (questionList != null) {
                                    if (questionList.size() > 0) {
                                        for (int i = 0; i < questionList.size(); i++) {
                                            VolunteerBean volunteerBean = new VolunteerBean();
                                            volunteerBean.setQuestion(questionList.get(i).getQuestion());
                                            volunteerBean.setIcon(questionList.get(i).getHeadimgurl());
                                            volunteerBean.setName(questionList.get(i).getName());
                                            volunteerBean.setPro_id(Constant.VOLUNTEER_ANSWER);
                                            volunteerBean.setTime(questionList.get(i).getQuestion_time());
                                            volunteerBean.setId(questionList.get(i).getDialog_id());
                                            volunteerBean.setType(questionList.get(i).getType());
                                            volunteerBean.setIsPay(questionList.get(i).getIspay());
                                            volunteerBean.setAnswerContent(questionList.get(i).getAnswer());
                                            arrayList.add(volunteerBean);
                                        }
                                    }
                                }
                                if (commentList != null) {
                                    if (commentList.size() > 0) {
                                        for (int i = 0; i < commentList.size(); i++) {
                                            VolunteerBean volunteerBean = new VolunteerBean();
                                            volunteerBean.setPro_id(Constant.VOLUNTEER_EVALUATE);
                                            volunteerBean.setName(commentList.get(i).getName());
                                            volunteerBean.setCommentContent(commentList.get(i).getContent());
                                            volunteerBean.setTime(commentList.get(i).getComment_time());
                                            volunteerBean.setIcon(commentList.get(i).getHeadimgurl());
                                            volunteerBean.setId(commentList.get(i).getComment_id());
                                            arrayList.add(volunteerBean);
                                        }
                                    }
                                }
                                stickyListHeaderListViewAdapter.notifyDataSetChanged();
                            }
                            break;
                        case FOCUS:
                            try {
                                JSONObject jsonObject = new JSONObject((String) msg.obj);
                                int status = jsonObject.getInt("status");
//                                getDataFromInternet(id);
                                if (status == 1) {
                                    //关注成功
                                    volunteer_focus.setImageResource(R.mipmap.volunteer_focused);
                                } else {
                                    //取消关注
                                    volunteer_focus.setImageResource(R.mipmap.volunteer_focus);
                                    changeFocus = true;
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                            break;
                        default:
                            break;
                    }
                    break;
                default:
                    break;
            }
        }
    };


    /***
     * 将activity 的创建模式设置为singletask,
     * 使用这个方法可以再其他activity想这个activity发送Intent时，这个Intent能够及时更新
     */
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        type = intent.getStringExtra("type");
        id = intent.getStringExtra("id");
        initView();
        initListView();
        //从志愿者列表中获得id
        if (id != null) {
            getDataFromInternet(id);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        type = getIntent().getStringExtra("type");
        id = getIntent().getStringExtra("id");
        initView();
        initListView();
        changeHeader();
        //从志愿者列表中获得id
        if (id != null) {
            getDataFromInternet(id);
        }
    }


    private void initView() {
        if(header==null) {
            header = LayoutInflater.from(this).inflate(R.layout.volunteer_header, null);
        }
        volunteer_head = (ImageView) header.findViewById(R.id.volunteer_head);
        volunteer_head_vip = (ImageView) header.findViewById(R.id.volunteer_head_vip);
        volunteer_header_satisfaction_ima = (ImageView) header.findViewById(R.id.volunteer_header_satisfaction_ima);
        volunteer_header_active_ima = (ImageView) header.findViewById(R.id.volunteer_header_active_ima);
        volunteer_brief = (TextView) header.findViewById(R.id.volunteer_brief);
        volunteer_name = (TextView) header.findViewById(R.id.volunteer_name);
        volunteer_header_attention = (TextView) header.findViewById(R.id.volunteer_header_attention);
        volunteer_header_answered = (TextView) header.findViewById(R.id.volunteer_header_answered);
        volunteer_header_satisfaction = (TextView) header.findViewById(R.id.volunteer_header_satisfaction);
        volunteer_header_active = (TextView) header.findViewById(R.id.volunteer_header_active);
        volunteer_content_department = (TextView) header.findViewById(R.id.volunteer_content_department);
        volunteer_content_major = (TextView) header.findViewById(R.id.volunteer_content_major);
        volunteer_content_college = (TextView) header.findViewById(R.id.volunteer_content_college);
        volunteer_focus = (ImageView) header.findViewById(R.id.volunteer_focus);
        volunteer_header_layout = (RelativeLayout) header.findViewById(R.id.volunteer_header_layout);
        volunteer_header_satisfaction_layout = (LinearLayout) header.findViewById(R.id.volunteer_header_satisfaction_layout);
        volunteer_back.setOnClickListener(this);
        volunteer_focus.setOnClickListener(this);
        volunteer_ask.setOnClickListener(this);
        volunteer_head.setOnClickListener(this);
        volunteer_introduction_layout = (LinearLayout) header.findViewById(R.id.volunteer_introduction_layout);
        volunteer_introduction = (TextView) header.findViewById(R.id.volunteer_introduction);
        volunteer_more_introduction = (ImageView) header.findViewById(R.id.volunteer_more_introduction);
        volunteer_introduction_layout.setOnClickListener(this);
        showImageUtils = new ShowImageUtils();
        switch (type) {
            case Constant.VOLUNTEER_TYPE_OFFICIAL:
                volunteer_brief.setVisibility(View.VISIBLE);
                volunteer_head_vip.setVisibility(View.VISIBLE);
                volunteer_introduction_layout.setVisibility(View.GONE);
                volunteer_header_attention.setVisibility(View.GONE);
                volunteer_header_answered.setVisibility(View.GONE);
                volunteer_focus.setVisibility(View.GONE);
                volunteer_header_satisfaction_layout.setVisibility(View.GONE);
                break;
            case Constant.VOLUNTEER_TYPE_VIP:
                volunteer_brief.setVisibility(View.GONE);
                volunteer_head_vip.setVisibility(View.GONE);
                volunteer_introduction_layout.setVisibility(View.VISIBLE);
                volunteer_header_attention.setVisibility(View.VISIBLE);
                volunteer_header_answered.setVisibility(View.VISIBLE);
                volunteer_focus.setVisibility(View.VISIBLE);
                volunteer_header_satisfaction_layout.setVisibility(View.VISIBLE);
                break;
            case Constant.VOLUNTEER_TYPE_NORMAL:
            default:
                volunteer_brief.setVisibility(View.GONE);
                volunteer_head_vip.setVisibility(View.GONE);
                volunteer_introduction_layout.setVisibility(View.GONE);
                volunteer_header_attention.setVisibility(View.GONE);
                volunteer_header_answered.setVisibility(View.GONE);
                volunteer_focus.setVisibility(View.GONE);
                volunteer_header_satisfaction_layout.setVisibility(View.GONE);
                break;
        }
    }

    private void initListView() {
        arrayList = new ArrayList<>();
        stickyListHeaderListViewAdapter = new VolunteerStickyListHeaderListViewAdapter(this, arrayList);
        if(listHeadersListView.getHeaderViewsCount()>0) {
            for (int i = 0; i < listHeadersListView.getHeaderViewsCount(); i++) {
                listHeadersListView.removeHeaderView(header);
            }
        }
        listHeadersListView.addHeaderView(header);
        listHeadersListView.setAdapter(stickyListHeaderListViewAdapter);
    }


    /**
     * 头部根据scrollview的滑动修改背景颜色
     */
    private void changeHeader() {
        volunteer_header_layout.measure(0, 0);
        volunteer_answer_item_header.measure(0, 0);
        measuredHeight = volunteer_header_layout.getMeasuredHeight() - volunteer_answer_item_header.getMeasuredHeight();
        listHeadersListView.setOnScrollListener(new AbsListView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (listViewScorllY(listHeadersListView) <= 0) {
                    volunteer_answer_item_header.setBackgroundColor(Color.argb(0, 8, 130, 238));//AGB由相关工具获得，或者美工提供
                    volunteer_answer_item_name.setTextColor(Color.argb(0, 255, 255, 255));
                } else if (listViewScorllY(listHeadersListView) > 0 && listViewScorllY(listHeadersListView) <= measuredHeight) {
                    float scale = (float) listViewScorllY(listHeadersListView) / measuredHeight;
                    float alpha = (255 * scale);
                    // 只是layout背景透明(仿知乎滑动效果)
                    volunteer_answer_item_header.setBackgroundColor(Color.argb((int) alpha, 8, 130, 238));
                    volunteer_answer_item_name.setTextColor(Color.argb((int) alpha, 255, 255, 255));
                } else {
                    volunteer_answer_item_header.setBackgroundColor(Color.argb(255, 8, 130, 238));
                    volunteer_answer_item_name.setTextColor(Color.argb(255, 255, 255, 255));
                }
            }
        });
    }


    private int listViewScorllY(StickyListHeadersListView mListView) {
        View view = mListView.getListChildAt(0);
        if (view == null) {
            return 0;
        }
        int firstVisiblePosition = mListView.getFirstVisiblePosition();
        int top = view.getTop();
        return -top + firstVisiblePosition * view.getHeight();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.volunteer_back:
                Intent data = new Intent();
                data.putExtra("changeFocus", changeFocus);
                Volunteer.this.setResult(1, data);
                Volunteer.this.finish();
                break;
            case R.id.volunteer_introduction_layout:
                if (isShowIntroduction) {
                    //展开个人简介
                    volunteer_introduction.setSingleLine(true);
                    volunteer_more_introduction.setImageResource(R.mipmap.volunteer_more_introduction_ima);
                    isShowIntroduction = false;
                } else {
                    volunteer_introduction.setSingleLine(false);
                    volunteer_more_introduction.setImageResource(R.mipmap.volunteer_hide_introduction_ima);
                    isShowIntroduction = true;
                }
                break;
            case R.id.volunteer_focus:
                EXPERTATTENTION(id);
                break;
            case R.id.volunteer_ask:
                //立即提问
                if (this.hasLoad()) {
                    Intent intent = new Intent(this, Ask.class);
                    intent.putExtra("id", id);
                    intent.putExtra("type", type);
                    startActivity(intent);
                } else {
                    this.login(this);
                }
                break;
            case R.id.volunteer_head:
                showImageUtils.showImageUtils(Volunteer.this, volunteer_head, consulter.getHeadimgurl());
                break;
            default:
                break;
        }
    }


    private void getDataFromInternet(String id) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("id", id);
        hashMap.put("type", type);
        new InterNetController(this, Constant.CONSULTERDETAIL, myHandler, hashMap, GETDATA);
    }

    //关注志愿者
    private void EXPERTATTENTION(String id) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("expert_id", id);
        new InterNetController(this, Constant.EXPERTATTENTION, myHandler, hashMap, FOCUS, false);
    }

    @Override
    public void onBackPressed() {
        Intent data = new Intent();
        data.putExtra("changeFocus", changeFocus);
        Volunteer.this.setResult(1, data);
        Volunteer.this.finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        showImageUtils = null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_CANCELED) {
            if (resultCode == Constant.PAY_SUCCESS) {
                int position = data.getIntExtra("position", 0);
                arrayList.get(position).setIsPay("1");
                stickyListHeaderListViewAdapter.notifyDataSetChanged();
            }
        }
    }
}
